package com.basker.pisces.context;

import org.springframework.core.NamedThreadLocal;
import org.springframework.lang.Nullable;

import com.basker.ttl.NamedTransmittableThreadLocal;

/**
 * {@link LoginContext}线程寄存器
 *
 * @author hangwen
 */
public class LoginContextHolder {
    private static final String NAME = LoginContextHolder.class.getSimpleName();

    private static final ThreadLocal<LoginContext> TL_HOLDER = new NamedThreadLocal<>(NAME);
    private static final ThreadLocal<LoginContext> TTL_HOLDER = new NamedTransmittableThreadLocal<>(NAME);

    public static LoginContext getLoginContext() {
        LoginContext lcx = TL_HOLDER.get();
        if (lcx == null) {
            lcx = TTL_HOLDER.get();
        }
        return lcx;
    }

    public static void remove() {
        TL_HOLDER.remove();
        TTL_HOLDER.remove();
    }

    public static void setLoginContext(@Nullable LoginContext lcx, boolean inheritable) {
        if (lcx == null) {
            return;
        }

        if (inheritable) {
            TTL_HOLDER.set(lcx);
            TL_HOLDER.remove();
        } else {
            TL_HOLDER.set(lcx);
            TTL_HOLDER.remove();
        }

    }
}
